<template>
    <el-dialog
        title="历史轨迹"
        v-model="state.isShowDialog"
        custom-class="route"
        append-to-body
        width="1200px"
        destroy-on-close
    >
        <div id="route-map" class="map-box" ref="mapRouteRef"></div>
        <div class="map-area">
            <el-card class="tool-window" style="width: 380px">
              <el-date-picker placeholder="请选择数据时间" value-format="YYYY/MM/DD" type="daterange"
                v-model="dataTimeRange"/>
                <div style="margin-top: 15px">
                  <el-button type="primary" @click="getList">查询</el-button>
                </div>
            </el-card>
        </div>
    </el-dialog>
</template>

<script lang="ts" setup name="route">
import { onMounted, ref,reactive,onUpdated } from 'vue';

import "ol/ol.css";
import { Map, View, Feature } from "ol";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import XYZ from "ol/source/XYZ";
import * as control from 'ol/control'
import { Vector as VectorSource } from "ol/source";
import { Style, Fill, Stroke, Circle as sCircle } from "ol/style";
import { Point, LineString } from "ol/geom";

import { getAPI } from "/@/axios-utils";
// import { Jt808DataApi } from '/@/api-services/api';
// import { MygpsDeviceDataInput,MYGPSJT808DATA } from '/@/api-services/models';

const mapRouteRef = ref(null);            // 地图容器
const mapRoute = ref<Map | undefined>();   // 地图实例
const dataTimeRange = ref<any[]>([]);
const value = ref();

const state = reactive({
    isShowDialog: false,
    routes: [],
    lastRouteIndex: 0,
    routesAll: [],
    EfenceData: [],
    speed: 10,
    routeGeometry: null,
    aisGeometry: null,
    aisFeature: null,
    animating: false,
});

const styles = Object.freeze({
  route: new Style({
    stroke: new Stroke({
      lineDash: [2, 6, 10],
      width: 4,
      color: [0, 255, 0, 1],
    }),
  }),
  marker: new Style({
    image: new sCircle({
      radius: 10,
      stroke: new Stroke({
        color: "#fff",
      }),
      fill: new Fill({
        color: "#3399CC",
      }),
    }),
  })
});

/**
 * 打开弹窗
 * @param row 
 */
const openDialog = (terminalPhoneNo: any) => {
  value.value = terminalPhoneNo;
	state.isShowDialog = true;
};

const getList = async () => {
  // const dataInput: MygpsDeviceDataInput = {
  //     page: 0,
  //     pageSize: 0,
  //     field: "",
  //     order: "",
  //     terminalPhoneNo: value.value,
  //     startTime: new Date(dataTimeRange.value[0] + " 00:00:00"),
  //     endTime: new Date(dataTimeRange.value[1] + " 23:59:59"),
  // };

  // var res = await getAPI(Jt808DataApi).apiJt808DataDatalistPost(dataInput);
  // let Data = res.data.result ?? [];
  // drawRoute(Data);
}

/**
 * 页面加载时
 */
onMounted(async () => {

});

onUpdated(() => {
  // if (mapRoute.value == null) {
    
  // }

  initMap();  // 初始化地图
  dataTimeRange.value = [setDefaultDate(0), setDefaultDate(1)];
});

// const drawRoute = (Data:MYGPSJT808DATA[])=>{
//   let layerVecor = mapRoute.value?.getLayers().getArray().find((a: { get: (arg0: string) => string; }) => a.get('layerName') == 'route')  // 查找AIS标记图层
//   let layerSource = layerVecor?.getLayersArray()[0].getSource()

//   layerSource?.clear();

//   state.routes = Data.map((item:MYGPSJT808DATA) => {
//     return [item.lng / 1000000, item.lat / 1000000];
//   });

//   state.routeGeometry = new LineString(state.routes);
//   let route = new Feature({
//     type: "route",
//     geometry: state.routeGeometry,
//   });

//   // 绘制点
//   let opints = drawPoint();

//   layerSource?.addFeatures([route, ...opints]);
// };

// 画点
// const drawPoint = () =>{
//   let iconFeatures = <any>[];
//     state.routes.forEach((item) => {
//     let _feature = new Feature({
//       type: "marker",
//       geometry: new Point(item),
//     });
//     iconFeatures.push(_feature);
//   });
//   return iconFeatures;
// }

const setDefaultDate = (
	type: number
): string => {
	let t = '';
	let date = new Date();
	let dateMap = {
		year: date.getFullYear(),
		month: date.getMonth() + 1,
		day: date.getDate(),
	};

	let month = dateMap.month >= 10 ? dateMap.month : "0" + dateMap.month
	let day = dateMap.day >= 10 ? dateMap.day : "0" + dateMap.day
	//当天默认初始时间 00:00:00
	if (type === 0) {
		t = date.getFullYear() + "-" + month + "-" + day;
	}

	//当天默认初始时间 23:59:59
	if (type === 1) {
		t = date.getFullYear() + "-" + month + "-" + day;
	}
	return t;
};

/**
 * 初始化地图
 */
const initMap = async () => {
  
  mapRoute.value = new Map({
      target: "route-map",
      view: new View({
          center: [118.80, 24.58],
          projection: 'EPSG:4326',
          zoom: 10,
          minZoom: 2,
          maxZoom: 18,
      }),
      //overlays: [overlay.value], // 绑定一个覆盖物
      layers: [
          new TileLayer({		// 瓦片图层
              source: new XYZ({
                  url: "http://t{0-4}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=f6a024281b465b39f7f7c293a7012c80"
              }),
              visible: true
          }),
          new TileLayer({	// 地理信息图层
              source: new XYZ({
                  url: "http://t{0-4}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=f6a024281b465b39f7f7c293a7012c80"
              }),
              visible: true
          })
      ],
      controls: control.defaults().extend([
          new control.ZoomSlider(), new control.Zoom()
      ]),
  });

  let routeLayer = new VectorLayer({
      source: new VectorSource({ wrapX: false }),
      style: (feature) => {
          return styles[feature.get("type")];
      },
  });
  routeLayer.set('layerName', 'route');    // 设置图层名称
  mapRoute.value?.addLayer(routeLayer);
}

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>

<style lang="scss" scoped>
.route {
  .el-dialog__header {
    padding: 20px;
  }
  .el-dialog__body {
    padding: 0;
    .map-area {
      box-shadow: inset 5em 1em #000000;
      position: relative;
      .tool-window {
        width: 200px;
        position: absolute;
        bottom: 20px;
        right: 20px;
        .button {
          font-size: 20px;
        }
        .speed {
          margin-top: 15px;
          display: flex;
          align-items: center;
          .speed-input {
            flex: 1;
            margin: 0 10px;
          }
        }
      }
    }
  }
}
.map-box {
  width: 100%;
  height: 60vh;
}
</style>